//
//  BaseViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/16.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "BaseViewController.h"
#import <CoreLocation/CoreLocation.h>


@interface BaseViewController () <CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager* locationManager;
@property (nonatomic, retain) NoContentView *noContentV;

@end

@implementation BaseViewController
- (void)dealloc
{
    [_noContentV release];
    [_locationManager release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.navigationController.navigationBar.translucent = NO;
    
    // 隐藏NavigationBar底部的黑线
    // NavigationBar底部的黑线是一个UIImageView上的UIImageView
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *listImageV = imageView.subviews;
                for (id objc in listImageV) {
                    if ([objc isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageV=(UIImageView *)objc;
                        imageV.hidden=YES;
                    }
                }
            }
        }
    }
    

    
    
     
    // 左button
    UIImage *leftImage = [[UIImage imageNamed:@"icons_back_dark@2x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *leftLandscapeImage = [[UIImage imageNamed:@"icons_back_bantou@2x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:leftImage landscapeImagePhone:leftLandscapeImage style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)] autorelease];

 
    
    // 接收夜间模式的通知
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isNightChange:) name:@"isNightChange" object:nil];
    
    [self changeColor];
 
}
- (void)noContentViewWithFrame:(CGRect)frame hidden:(BOOL)hidden
{
    if (nil == _noContentV) {
        self.noContentV = [[NoContentView alloc] initWithFrame:frame];
        self.noContentV.hidden = YES;
        [self.view addSubview:self.noContentV];
        [_noContentV release];
    }
    self.noContentV.hidden = hidden;
}

- (void)leftAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)isNightChange:(NSNotification *)sender
{
    NSString *str = [sender object];
    
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"isNight"];
    
    [self changeColor];
}
- (void)changeColor
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isNight"] isEqualToString:@"1"]) {
        
        // 夜间模式
        
        // view背景图
        [ColorSingleton shareSingleton].viewBackgroundColor = [UIColor colorWithRed:0.12 green:0.12 blue:0.12 alpha:1];
        // 系统navigBar字体颜色
        [ColorSingleton shareSingleton].navigationBarTextColor = [UIColor colorWithRed:0.56 green:0.56 blue:0.56 alpha:1];
        // navigBar 自定义的颜色
        [ColorSingleton shareSingleton].myNavigationBarTextColor = [UIColor whiteColor];
        // navigBar背景颜色
        [ColorSingleton shareSingleton].barTintColor = [UIColor colorWithRed:0.05 green:0.05 blue:0.05 alpha:1];
        // cell背景颜色
        [ColorSingleton shareSingleton].cellColor = [UIColor colorWithRed:0.17 green:0.17 blue:0.17 alpha:1];
        // cell标题颜色
        [ColorSingleton shareSingleton].cellTitleColor = [UIColor lightGrayColor];
        // cell分割线颜色
        [ColorSingleton shareSingleton].cellLineColor = [UIColor colorWithRed:0.12 green:0.12 blue:0.12 alpha:1];
        
        // 地址页面分区头背景
        [ColorSingleton shareSingleton].sectionBackgroundColor = [UIColor colorWithRed:0.17 green:0.17 blue:0.17 alpha:1];
        
        // 没有选择的边框
        [ColorSingleton shareSingleton].offViewBorderColor = [UIColor colorWithRed:0.12 green:0.12 blue:0.12 alpha:1];
        // 选择的边框
        [ColorSingleton shareSingleton].onViewBorderColor = [UIColor blackColor];
    } else {
        // 白天模式
        
        // view背景图
        [ColorSingleton shareSingleton].viewBackgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
        // 系统navigBar字体颜色
        [ColorSingleton shareSingleton].navigationBarTextColor = NAVG_FONTCOLOR_ON;
        // navigBar 自定义的颜色
        [ColorSingleton shareSingleton].myNavigationBarTextColor = NAVG_FONTCOLOR_ON;
        // navigBar背景颜色
        [ColorSingleton shareSingleton].barTintColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1];
        // cell背景颜色
        [ColorSingleton shareSingleton].cellColor = [UIColor whiteColor];
        // cell标题颜色
        [ColorSingleton shareSingleton].cellTitleColor = [UIColor colorWithRed:0.14 green:0.01 blue:0 alpha:1];
        // cell分割线颜色
        [ColorSingleton shareSingleton].cellLineColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
        
        // 地址页面分区头背景
        [ColorSingleton shareSingleton].sectionBackgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
        // 没有选择的边框
        [ColorSingleton shareSingleton].offViewBorderColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
        
        // 选择的边框
        [ColorSingleton shareSingleton].onViewBorderColor = [UIColor colorWithRed:0.96 green:0.67 blue:0.68 alpha:1];
        
    }
    
    self.view.backgroundColor = [ColorSingleton shareSingleton].viewBackgroundColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[ColorSingleton shareSingleton].navigationBarTextColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18.f]};
    self.navigationController.navigationBar.barTintColor = [ColorSingleton shareSingleton].barTintColor;
    
    self.tabBarController.tabBar.barTintColor = [ColorSingleton shareSingleton].barTintColor;
}
- (void)NetworkError:(Block)block
{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"网络错误"message:@"请检查网络错误" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        block();
    }];

    [alertC addAction:action1];
    [self presentViewController:alertC animated:YES completion:nil];
}




#pragma mark - 定位相关
- (void)sendDefault:(NSString *)str
{
    NSLog(@"定位成功 - 发送通知:")
    // 发送通知 刷新订阅
    [[NSNotificationCenter defaultCenter] postNotificationName:@"location" object:str];
}
//开始定位
-(void)startLocation {

    // 判断系统定位服务有没有打开
    if([CLLocationManager locationServicesEnabled]) {
        
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 3000.f;
        [_locationManager requestWhenInUseAuthorization];//添加这句
        [self.locationManager startUpdatingLocation];
        
    } else {
        [self sendDefault:@"定位服务未打开"];
    }
}
// 判断当前应用的定位状态
- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    
    NSString *errorString;
    [manager stopUpdatingLocation];
    //    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"Access to Location Services denied by user";
            [self sendDefault:@"定位不可用"];
            //Do something...
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"Location data unavailable";
            [self sendDefault:@"定位失败"];
            //Do something else...
            break;
        default:
            errorString = @"An unknown error has occurred";
            [self sendDefault:@"未知的错误"];
            break;
    }
}

//定位代理经纬度回调
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [_locationManager stopUpdatingLocation];
    
    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            
            [self sendDefault:city];
        }
    }];
    
    
}
// color转换成image
- (UIImage*) createImageWithColor: (UIColor *) color
{
    CGRect rect=CGRectMake(0,0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
